package com.cxria.shiro.shiro.filter;

import com.cxria.shiro.dto.ShiroStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Locale;

public class JsonResultLogoutFilter extends LogoutFilter {

	private final Logger log = LoggerFactory.getLogger(LogoutFilter.class);

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

		Subject subject = getSubject(request, response);

		if (isPostOnlyLogout()) {
			if (!WebUtils.toHttp(request).getMethod().toUpperCase(Locale.ENGLISH).equals("POST")) {
				return onLogoutRequestNotAPost(request, response);
			}
		}

		try {
			subject.logout();
		} catch (SessionException ise) {
			log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
		}
		response.setContentType("application/json;charset=UTF-8");
		ShiroStatus status = new ShiroStatus();
		response.getWriter().append(objectMapper.writeValueAsString(status));
		return false;
	}

}
